package io.zhiller.simpletemplate.utils.vanilla

import android.content.Context
import kotlinx.io.IOException
import java.io.File
import java.io.FileInputStream
import java.io.FileOutputStream

object FileUtils {
  fun getFileExtension(fileName: String): String {
    return fileName.substringAfterLast(".", "")
  }
  
  fun getFilePathWithoutExtension(fileName: String): String {
    return fileName.substringBeforeLast(".")
  }
  
  fun getFileNameWithExtension(fileName: String): String {
    return fileName.substringAfterLast("/")
  }
  
  fun getFileNameWithoutExtension(fileName: String): String {
    val fullName = fileName.substringAfterLast("/")
    return fullName.substringBeforeLast(".")
  }
  
  fun getFileExternal(context: Context, fileDir: String, fileName: String): File {
    return File(context.getExternalFilesDir(fileDir), fileName)
  }
  
  // 获取内部存储应用目录
  fun getInternalAppPath(context: Context): String {
    return context.filesDir.absolutePath
  }
  
  // 获取外部存储应用目录
  fun getExternalAppPath(context: Context): String {
    return context.getExternalFilesDir("")?.absolutePath ?: ""
  }
  
  // 创建文件
  fun createFile(path: String, fileName: String): Boolean {
    val file = File(path, fileName)
    return if (!file.exists()) {
      try {
        file.createNewFile()
        true
      } catch (e: IOException) {
        e.printStackTrace()
        false
      }
    } else {
      false
    }
  }
  
  // 创建文件夹
  fun createDirs(folderPath: String): Boolean {
    val folder = File(folderPath)
    return if (!folder.exists()) {
      folder.mkdirs()
      true
    } else {
      false
    }
  }
  
  // 删除文件
  fun deleteFile(filePath: String): Boolean {
    val file = File(filePath)
    return if (file.exists() && file.isFile) {
      file.delete()
      true
    } else {
      false
    }
  }
  
  // 删除文件夹及其内部所有文件和文件夹
  fun deleteDir(dirPath: String) {
    val dir = File(dirPath)
    if (dir.exists()) {
      deleteDirWithFile(dir)
    }
  }
  
  private fun deleteDirWithFile(file: File) {
    if (!file.isDirectory || !file.exists()) {
      return
    }
    if (file.list()?.isNotEmpty() == true) {
      for (f in file.listFiles()!!) {
        if (f.isFile) {
          f.delete()
        } else if (f.isDirectory) {
          deleteDirWithFile(f)
        }
      }
    }
    file.delete()
  }
  
  // 复制文件
  fun copyFile(oldPath: String, newPath: String) {
    try {
      val inputStream = FileInputStream(oldPath)
      val outputStream = FileOutputStream(newPath)
      val buffer = ByteArray(1024)
      var length: Int
      while (inputStream.read(buffer).also { length = it } > 0) {
        outputStream.write(buffer, 0, length)
      }
      inputStream.close()
      outputStream.close()
    } catch (e: IOException) {
      e.printStackTrace()
    }
  }
  
  // 移动文件
  fun moveFile(oldPath: String, newPath: String) {
    copyFile(oldPath, newPath)
    deleteFile(oldPath)
  }
  
  // 检查文件是否存在
  fun fileExists(filePath: String): Boolean {
    val file = File(filePath)
    return file.exists()
  }
  
  // 获取文件夹下的所有文件和文件夹
  fun listFilesInDir(dirPath: String): Array<File>? {
    val dir = File(dirPath)
    return if (dir.exists() && dir.isDirectory) {
      dir.listFiles()
    } else {
      null
    }
  }
  
  // 从文件路径获取文件大小
  fun getFileSizeFromPath(filePath: String): Long {
    val file = File(filePath)
    return if (file.exists() && file.isFile) {
      file.length()
    } else {
      0
    }
  }
  // 获取文件大小
  fun getFileSize(file: File): Long {
    return if (file.exists() && file.isFile) {
      file.length()
    } else {
      0
    }
  }
  
  fun convertFileSize(sizeInBytes: Long): String {
    val kiloByte = 1024.0
    val megaByte = kiloByte * kiloByte
    val gigaByte = megaByte * kiloByte
    return when {
      sizeInBytes < kiloByte -> "$sizeInBytes B"
      sizeInBytes < megaByte -> "%.2fKB".format(sizeInBytes / kiloByte)
      sizeInBytes < gigaByte -> "%.2fMB".format(sizeInBytes / megaByte)
      else -> "%.2fGB".format(sizeInBytes / gigaByte)
    }
  }
}